<script setup>
import {onMounted, ref} from 'vue'
import { Plus, Sort, SortUp, SortDown } from '@element-plus/icons-vue'
import axios from "axios";
import dayjs from 'dayjs';
import {router} from "@/router/index.js";
import {useRoute} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import AddAndEditCategory from "@/views/MallManagement/AddAndEditCategory.vue";

// 查询表单
const queryForm = ref({
  categoryName: '',
  startDate:'',
  endDate:'',
})

// 表格数据
const tableData = ref([])
const CategoryId = ref(-1);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);


const initData=()=>{
  axios.get(`/category/getAll/${pageSize.value}/${currentPage.value}`).then((res)=>{
    tableData.value = res.data.data;
    console.log(tableData.value)
    total.value = res.data.total;
  })
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  initData();
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  initData();
}

// 选中的行的id
const selectedRows = ref([])
const options = ref([])


const selectCategoryName = ()=>{
  axios.get(`/category/getCategoryName`).then(resp=>{
    options.value = resp.data;
  })
}



onMounted( ()=>{
  initData()
  selectCategoryName()
})

// 查询
const handleQuery = () => {
  axios.post(`/category/getByCategoryAndTime`,queryForm.value).then(resp=>{
    tableData.value = resp.data;
  })
}

// 重置查询
const resetQuery = () => {
  queryForm.value = {
    categoryName: '',
    startDate:'',
    endDate:'',
  }
}

// 新增
const handleAdd = () => {
  router.push('/addAndEditCategory')
}

// 下架
const handleOffShelf = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  ElMessageBox.confirm('确定要下架这些品类吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`/category/removeCategoryByIds/${selectedRows.value}`).then((res) => {
      initData()
      ElMessage.success(res.data)
    })

  }).catch(() => {
    ElMessage.info('已取消下架')
  })
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection.map(row => row.id);
}

// 编辑
const handleEdit = (row) => {
  CategoryId.value = row.id;
  router.push(`addAndEditCategory?categoryId=${CategoryId.value}`)
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该品类吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`/category/deleteCategoryById/${row.id}`).then((res) => {
      initData()
      ElMessage.success(res.data)
    })

  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 查看
const handleView = (row) => {
  CategoryId.value = row.id;
 router.push(`viewCategory?categoryId=${CategoryId.value}`)
}

const formatDateTime = (dateString) => {
  return dateString ? dayjs(dateString).format('YYYY-MM-DD HH:mm:ss') : ''
}
</script>

<template>
  <div class="category-management">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商城系统</el-breadcrumb-item>
      <el-breadcrumb-item>品类管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 标题 -->
    <h2 class="page-title">品类管理</h2>

    <!-- 查询条件 -->
    <div class="query-conditions">
      <h3 class="query-title">查询条件</h3>
      <el-form :inline="true" :model="queryForm">
        <el-form-item label="一级品类：" class="category-select">
          <el-select
              v-model="queryForm.categoryName"
              placeholder="全部"
              class="custom-select"
              clearable
              filterable
          >
            <el-option
                v-for="(item, index) in options"
                :key="index"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="创建日期：">
          <div class="date-range-split">
            <el-date-picker
                v-model="queryForm.startDate"
                type="date"
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
                style="width: 140px"
            />
            <span class="date-range-separator">至</span>
            <el-date-picker
                v-model="queryForm.endDate"
                type="date"
                placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 140px"
            />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
      <el-button type="warning" @click="handleOffShelf">下架</el-button>
    </div>

    <!-- 表格数据 -->
    <el-table
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="品类ID" width="120" />
      <el-table-column prop="categoryName" label="品类名称" width="150" />
      <el-table-column prop="sortOrder" label="顺序" width="120">
        <template #header>
          <div class="sort-header" @click="toggleSort">
            <span>顺序</span>
            <component :is="sortIcon" class="sort-icon" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="subCategories" label="子品类">
        <template #default="{ row }">
          <el-tag
              v-for="(item, index) in row.subCategories.split('/')"
              :key="index"
              size="small"
              class="sub-category-tag"
          >
            {{ item }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          <el-button size="small" @click="handleView(row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination" >
      <ElPagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[3, 10, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<style scoped>
.category-management {
  padding: 20px;
}

.page-title {
  margin: 20px 0;
  font-size: 20px;
  font-weight: bold;
}

.query-conditions {
  background-color: #f5f7fa;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.action-buttons {
  margin-bottom: 20px;
}

.tip-text {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}

.sub-category-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.sort-header {
  display: flex;
  align-items: center;
  cursor: pointer;
  height: 100%;
}

.sort-icon {
  margin-left: 5px;
  font-size: 1em;
  width: 1em;
  height: 1em;
  vertical-align: middle;
}

/* 下拉框样式调整 */
.category-select {
  margin-right: 20px;
}

.custom-select {
  width: 220px;
}

.custom-select :deep(.el-input__inner) {
  height: 36px;
  line-height: 36px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.2s;
}

.custom-select :deep(.el-input__inner:hover) {
  border-color: #c0c4cc;
}

.custom-select :deep(.el-input__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.custom-select :deep(.el-select__caret) {
  color: #909399;
  font-size: 14px;
  transition: transform 0.2s;
}

.custom-select :deep(.el-select-dropdown__item) {
  padding: 0 20px;
  height: 36px;
  line-height: 36px;
  transition: background-color 0.2s;
}

.custom-select :deep(.el-select-dropdown__item.hover),
.custom-select :deep(.el-select-dropdown__item:hover) {
  background-color: #f5f7fa;
}

.custom-select :deep(.el-select-dropdown__item.selected) {
  color: #409eff;
  font-weight: normal;
  background-color: #f0f7ff;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.query-conditions {
  background-color: #f9fafc;
  padding: 24px;
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.query-conditions .el-form-item {
  margin-bottom: 16px;
  margin-right: 32px;
}

.date-range-split {
  display: flex;
  align-items: center;
}

.date-range-separator {
  margin: 0 10px;
  color: #666;
  font-size: 14px;
}

/* 控件高度统一 */
.custom-select :deep(.el-input__inner),
.date-range-split .el-date-editor {
  height: 36px !important;
  line-height: 36px !important;
}
</style>